#coding=utf-8
from starDB import *
import bottle
from bottle import static_file,request,route,post
import os


httpPort = '1426'

@route('/')
def starfile():
    return static_file('index.html', root=os.path.dirname(__file__))

@route('/<path:path>')
def starfile(path):
    return static_file(path, root=os.path.dirname(__file__))

def starllm(question):
    from http import HTTPStatus
    from dashscope import Application
    response = Application.call(app_id='da21a31e5656413e87e220fc26f176a9',
                                prompt=question,
                                api_key='sk-e85b22ce6e2e47058ae83fb7ce813165',
                                )

    if response.status_code != HTTPStatus.OK:
        return False
    else:
        return response.output

import json
@post('/login')
def login():
    res=checkPsw(request.forms['id'],request.forms['psw'])
    return json.dumps(res)

@post('/register')
def register():
    return json.dumps(addUsr(request.forms))

@post('/update')
def update():
    return json.dumps(updateUsr(request.forms))

@post('/password')
def password():
    return json.dumps(changePsw(request.forms))

@post('/sendMessage')
def sendMessage():
    sendChart(request.forms)
    import time
    aiReply = starllm(request.forms['msg'])
    #aiReply = FalseReply
    if(aiReply):
        sendChart({
            "id1":request.forms['id2'],
            "id2":request.forms['id1'],
            "msg":aiReply['text'],
            "ref":json.dumps(aiReply['doc_references'])
        })
        return json.dumps({
            "usr":{"id":"XiaoC","nickname":"小C","avatar":"1"},
            "msg":aiReply['text'],
            "ref":json.dumps(aiReply['doc_references']),
            "cts":int(time.time()*1000)
        })
    else:
        return json.dumps({
            "usr":{"id":"XiaoC","nickname":"小C","avatar":"1"},
            "msg":"发生错误了，我有点头疼，需要休息一会!",
            "ref":"",
            "cts":int(time.time()*1000)
        })

@post('/getMessage')
def getMessage():
    return json.dumps(getChart(request.forms['id1'],request.forms['id2'],request.forms['num']))

#bottle-http服务器实体
def httpServer():
    try:
        bottle.run(server="cheroot",host='0.0.0.0', port=httpPort)
    except:
        bottle.run(server="paste",host='0.0.0.0', port=httpPort)
if __name__=="__main__":
    httpServer()